package com.bayss.core.service.activity;

import com.bayss.core.DokoServerException;
import com.bayss.core.DokoServerExceptionFactor;
import com.bayss.core.entity.activity.ObgRechargeActivity;
import com.bayss.core.entity.activity.ObgRechargeActivityExample;
import com.bayss.core.entity.activity.mapper.ObgRechargeActivityMapper;
import com.bayss.core.entity.rbac.OBGUserInfo;
import com.bayss.core.entity.rbac.mapper.OBGUserInfoMapper;
import com.bayss.core.entity.user.TransactionRecord;
import com.bayss.core.entity.user.TransactionRecordExample;
import com.bayss.core.entity.user.UserInfo;
import com.bayss.core.entity.user.mapper.TransactionRecordMapper;
import com.bayss.core.entity.user.mapper.UserInfoMapper;
import com.bayss.core.enums.PayOrigin;
import com.bayss.core.enums.RechargeActivityStatus;
import com.bayss.core.service.homepage.ActivityService;
import com.bayss.core.service.pay.PayService;
import com.bayss.core.util.OrderUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by LDL on 2020/1/9.
 */
@Service
public class ObgRechargeActivityService {
    private static Logger logger = LogManager.getLogger();
    @Autowired
    private ObgRechargeActivityMapper rechargeActivityMapper;
    @Autowired
    private TransactionRecordMapper transactionRecordMapper;
    @Autowired
    private PayService payService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private OBGUserInfoMapper obgUserInfoMapper;


    /**
     * 储值活动新增
     *
     * @param obgRechargeActivity
     */
    public void saveObgRechargeActivity(ObgRechargeActivity obgRechargeActivity) {
        obgRechargeActivity.setStatus(Byte.valueOf("1"));
        obgRechargeActivity.setCreateTime(new Date());
        rechargeActivityMapper.insertSelective(obgRechargeActivity);
    }

    /**
     * 储值活动删除
     *
     * @param id
     */
    public void deleteObgRechargeActivity(Integer id) {
        rechargeActivityMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改
     *
     * @param activity
     */
    public void updateObgRechargeActivity(ObgRechargeActivity activity) {
        rechargeActivityMapper.updateByPrimaryKeySelective(activity);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageInfo<ObgRechargeActivity> listPages(int page, int pageSize) {
        ObgRechargeActivityExample example = new ObgRechargeActivityExample();
        example.setOrderByClause("create_time desc");
        PageInfo<ObgRechargeActivity> result = PageHelper.startPage(page, pageSize).doSelectPageInfo(() -> rechargeActivityMapper.selectByExample(example));
        for(ObgRechargeActivity e:result.getList()) {
            OBGUserInfo userInfo = obgUserInfoMapper.selectByPrimaryKey(e.getOperatorId());
            e.setOperatorName(userInfo == null ? "" : userInfo.getNickname());
        }
        return result;
    }

    /**
     * 查询所有可用的
     *
     * @return
     */
    public List<ObgRechargeActivity> list() {
        ObgRechargeActivityExample example = new ObgRechargeActivityExample();
        example.createCriteria().andStatusEqualTo(Byte.valueOf(RechargeActivityStatus.normal.getVal() + ""));
        return rechargeActivityMapper.selectByExample(example);
    }

    /**
     * 充值
     *
     * @param userInfo
     * @param amount     原金额
     * @param activityId
     * @return
     */
    public String recharge(UserInfo userInfo, Integer amount, Integer activityId) {
        TransactionRecord record = new TransactionRecord();
        record.setAmount(amount);

        if (activityId != null) {
            //充值活动
            ObgRechargeActivity activity = rechargeActivityMapper.selectByPrimaryKey(activityId);
            if (activity != null && amount >= activity.getAmount()) {
                record.setAmount(amount + activity.getMinusAmount());
            }
        }
        record.setUid(userInfo.getId());
        record.setActualAmount(amount);
        record.setTransactionType(Byte.valueOf("1"));
        record.setRechargeId(activityId);
        record.setRemark("充值");
        record.setCreateTime(new Date());
        record.setStatus(0);
        record.setOrderNo(OrderUtils.getRechargeNo(userInfo.getId()));

        transactionRecordMapper.insertSelective(record);
        try {
            return payService.payOrder(userInfo.getOpenId(), record.getOrderNo(), userInfo.getId(), String.valueOf(record.getActualAmount()), PayOrigin.RECHARGE, "");
        } catch (Exception e) {
            logger.error("支付信息失败", e);
            throw new DokoServerException(DokoServerExceptionFactor.ACTIVITY_APPLY_FAILED);
        }
    }

    /**
     * 充值成功回调方法
     * @param orderNo
     */
    public void rechargeCallBack(String orderNo) {
        logger.info("充值回调："+orderNo);

        //交易记录
        TransactionRecordExample example = new TransactionRecordExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);
        List<TransactionRecord> list = transactionRecordMapper.selectByExample(example);
        TransactionRecord recordDB = list.get(0);
        recordDB.setStatus(1);
        transactionRecordMapper.updateByPrimaryKeySelective(recordDB);

        //用户余额充值
        userInfoMapper.updateUserBalance(recordDB.getUid().intValue(), recordDB.getAmount());

        //用户类型升级为会员
        UserInfo userInfoQuery = new UserInfo();
        userInfoQuery.setId(recordDB.getUid());
        userInfoQuery.setType(2);
        userInfoMapper.updateByPrimaryKeySelective(userInfoQuery);
    }
}
